package com.gensdai.leliang.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bluelinelabs.logansquare.LoganSquare;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.common.bean.ProvinceJsonBean;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.dialog.UserSexDialog;
import com.gensdai.leliang.entity.User;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.utils.GetJsonDataUtil;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2017/7/3.
 */

public class UserCenter extends BaseActivityNoAbs implements View.OnClickListener {
    @BindView(R.id.ui_title)
    TextView uiTitle;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.binding_img)
    SimpleDraweeView bindingImg;
    @BindView(R.id.binding_img_ly)
    LinearLayout bindingImgLy;
    @BindView(R.id.binding_name)
    TextView bindingName;
    @BindView(R.id.binding_name_ly)
    LinearLayout bindingNameLy;
    @BindView(R.id.binding_sex)
    TextView bindingSex;
    @BindView(R.id.binding_sex_ly)
    LinearLayout bindingSexLy;
    @BindView(R.id.binding_area) //地区
            TextView bindingArea;
    @BindView(R.id.binding_area_ly)
    LinearLayout bindingAreaLy;
    @BindView(R.id.binding_phone)
    TextView bindingPhone;
    @BindView(R.id.binding_phone_ly)
    LinearLayout bindingPhoneLy;
    @BindView(R.id.binding_mail)
    TextView bindingMail;
    @BindView(R.id.binding_mail_ly)
    LinearLayout bindingMailLy;
    @BindView(R.id.exit_button)
    TextView ExitButton;
    @BindView(R.id.binding_yunyuset)
    TextView bindingYunyuset;
    @BindView(R.id.yunyuset)
    LinearLayout yunyuset;
    @BindView(R.id.binding_shejiao)
    TextView bindingShejiao;
    @BindView(R.id.shejiaobangding)
    LinearLayout shejiaobangding;

    private Upload up;
    SharedPreferences share;
    SharedPreferences.Editor ed;
    UserSexDialog sexDialog;
    User user = null;

    String path;//头像图片路径
    String paths;//头像图片路径
    private Uri mOutPutFileUri;

    private final int ENTER = 2;
    private final int SELECT = 1;
    private final int QUERY = 3;

    private final int IMAGE_RESULT_CODE = 2;// 表示打开照相机
    private final int PICK = 1;// 选择图片库
    private final int CHOOSE_PICTURE = 999;// 选择图片库

    private Thread thread;
    private static final int MSG_LOAD_DATA = 90001;
    private static final int MSG_LOAD_SUCCESS = 90002;
    private static final int MSG_LOAD_FAILED = 90003;
    private boolean isLoaded = false;

    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            ed.putString("img", user.getHandpic());
                            ed.putString("user_name", bindingName.getText().toString().trim());
                            ed.commit();
                        }
                        Toast.makeText(
                                UserCenter.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case SELECT:

                    break;
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

//                        Toast.makeText(New_delivery_address.this, "开始解析数据", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case QUERY:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            user = (User) new json_base().JsonUserInfo(new JSONObject((String) msg.obj));
                            if (user != null || user.getHandpic().length() > 5) {
                                Uri uri = Uri.parse(user.getHandpic());
                                bindingImg.setImageURI(uri);
                                ed.putString("img", user.getHandpic());
                            }
                            if (!user.getNickName().equals("null")) {
                                bindingName.setVisibility(View.VISIBLE);
                                bindingName.setText(user.getNickName());
                                ed.putString("user_name", user.getNickName());
                            }
                            if (!user.getSex().equals("null")) {
                                bindingSex.setVisibility(View.VISIBLE);
                                bindingSex.setText(user.getSex());
                            }
                            if (!user.getProvince().equals("null")) {
                                bindingArea.setVisibility(View.VISIBLE);
                                bindingArea.setText(user.getProvince() + user.getDistrict() + user.getCity());
                            }
                            if (!user.getEmail().equals("null")) {
                                bindingMail.setVisibility(View.VISIBLE);
                                bindingMail.setText(user.getEmail());
                            }
                            if (!user.getUserPregnantState().equals("null")) {
                                bindingYunyuset.setText(user.getUserPregnantState());
                                bindingYunyuset.setVisibility(View.VISIBLE);
                            }
                            ed.commit();
                        } else {
                            Toast.makeText(
                                    UserCenter.this,
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        ed.putBoolean("enter_state", false);
                        ed.putString("phone", "");
                        ed.putString("password", "");
                        ed.putString("WXopenid", "");
                        ed.putString("QQopenid", "");
                        ed.commit();
                        Intent go_enter = new Intent(UserCenter.this, user_enter.class);
                        startActivity(go_enter);
                        UserCenter.this.finish();
                    }

                    break;
                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(New_delivery_address.this, "解析数据成功", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
//                    Toast.makeText(New_delivery_address.this, "解析数据失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_center);
        ButterKnife.bind(this);
        init();
    }

    /**
     * 初始化
     */
    private void init() {

        //开启数据解析
        handler.sendEmptyMessage(MSG_LOAD_DATA);
        //end

        uiTitle.setText("个人中心");
        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        up = new Upload(this);
        bindingPhone.setText(share.getString("phone", ""));

        back.setOnClickListener(this);
        bindingAreaLy.setOnClickListener(this);
        ExitButton.setOnClickListener(this);
        bindingMail.setOnClickListener(this);
        bindingSex.setOnClickListener(this);
        bindingPhoneLy.setOnClickListener(this);
        bindingNameLy.setOnClickListener(this);
        bindingImgLy.setOnClickListener(this);
        shejiaobangding.setOnClickListener(this);
        yunyuset.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.exit_button:  //退出当前用户
                ed.putBoolean("enter_state", false);
//                ed.putString("phone", "");
                ed.putString("password", "");
                ed.putString("userno", "");
                ed.putString("user_id", "");
                ed.putString("WXopenid", "");
                ed.putString("QQopenid", "");
//                ed.putString("user_name", "");
//                ed.putString("phone", "");
                //put权限 0：无权限、1：有权限
                ed.putString("myWallet", "");
                ed.putString("bindAlipay", "");
                ed.putString("contactUs", "");
                ed.putString("receiveAddress", "");
                ed.putString("changePassword", "");
                ed.putString("inviteFriends", "");
                ed.putString("myCollection", "");
                ed.putString("memberType", "");
                ed.commit();
                Intent go_enter = new Intent(this, user_enter.class);
                startActivity(go_enter);
                this.finish();
                break;
            case R.id.binding_img_ly: // 修改头像

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                    // 检查该权限是否已经获取
                    int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        // 如果没有授予该权限，就去提示用户请求
                        showDialogTipUserRequestPermission();
                    } else {
                        sexDialog = new UserSexDialog(this, 3);
                        sexDialog.show();
                    }
                } else {
                    sexDialog = new UserSexDialog(this, 3);
                    sexDialog.show();
                }

                break;
            case R.id.binding_mail: // 绑定邮箱
                Intent go_mail = new Intent(this, BindingMail.class);
                startActivity(go_mail);
//                this.finish();
                break;
            case R.id.shejiaobangding: // 社交账户绑定
                Intent go_Set_social = new Intent(this, Set_social.class);
                startActivity(go_Set_social);
//                this.finish();
                break;
            case R.id.yunyuset: // 孕育设置
                if (user.getUserPregnantState().equals("已有宝宝")) {
                    Intent go_byz = new Intent(this, Set_yunyu_xq.class);
                    go_byz.putExtra("title", "我的宝宝");
                    go_byz.putExtra("state", "5");
                    startActivity(go_byz);

                } else if (user.getUserPregnantState().equals("怀孕中")) {
                    Intent go_hyz = new Intent(this, Set_yunyu_xq.class);
                    go_hyz.putExtra("title", "我的宝宝");
                    go_hyz.putExtra("state", "4");
                    startActivity(go_hyz);

                } else if (user.getUserPregnantState().equals("备孕中")) {
                    Intent go_byz = new Intent(this, Set_yunyu_xq.class);
                    go_byz.putExtra("title", "我的宝宝");
                    go_byz.putExtra("state", "3");
                    startActivity(go_byz);
                } else {
                    Intent go_yunyuset = new Intent(this, Set_yunyu.class);
                    startActivity(go_yunyuset);
                }
//                this.finish();
                break;
            case R.id.binding_phone_ly: // 修改手机号
                Intent go_Set_phone = new Intent(this, Set_phone.class);
                startActivity(go_Set_phone);
//                this.finish();
                break;
            case R.id.binding_sex: // 选择性别
                sexDialog = new UserSexDialog(this, 1);
                sexDialog.show();
                break;
            case R.id.binding_name_ly: // 修改昵称
                sexDialog = new UserSexDialog(this, 2);
                sexDialog.show();
                break;
            case R.id.binding_area_ly:

//                hideKeyBoard(this,phone_Number);

                if (isLoaded) {
                    ShowPickerView();
                } else {
//                    Toast.makeText(New_delivery_address.this, "数据暂未解析成功，请等待", Toast.LENGTH_SHORT).show();
                }
                break;


            case R.id.photograph: // 拍照
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                //文件夹peoto
                String path;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    //SD卡已装入
                    path = Environment.getExternalStorageDirectory().getPath() + "/peoto";
                } else {
                    path = this.getExternalFilesDir(null).getPath() + "/peoto";
                }
                paths = path;
                File path1 = new File(path);
                try {
                    if (!path1.exists()) {
                        path1.mkdirs();
                    }
                    File file = new File(path1, System.currentTimeMillis() + ".jpg");
                    mOutPutFileUri = Uri.fromFile(file);

                    ContentValues contentValues = new ContentValues(1);
                    contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
                    Uri uri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intent, IMAGE_RESULT_CODE);
                    sexDialog.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.photo_album: // 选相册
                Intent xiangce = new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
                xiangce.addCategory(Intent.CATEGORY_OPENABLE);
                xiangce.setType("image/jpeg");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    Intent it = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    it.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(it, CHOOSE_PICTURE);
//                    startActivityForResult(xiangce, PICK);
                } else {
                    startActivityForResult(xiangce, PICK);
                }// 打开照相机
                sexDialog.dismiss();
                break;
            case R.id.man: // 男
                Query(2, "0");
                bindingSex.setText("男");
                bindingSex.setVisibility(View.VISIBLE);
                sexDialog.dismiss();
                break;
            case R.id.weman: // 女
                Query(2, "1");
                bindingSex.setText("女");
                bindingSex.setVisibility(View.VISIBLE);
                sexDialog.dismiss();
                break;
            case R.id.y: // 确定
                Query(1, sexDialog.getName());
                bindingName.setText(sexDialog.getName());
                bindingName.setVisibility(View.VISIBLE);
                sexDialog.dismiss();
                break;
            case R.id.b: // 取消
                sexDialog.dismiss();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (share.getBoolean("enter_state", false)) {
            QueryNews();
        } else {
            Intent go_enter = new Intent(this, user_enter.class);
            startActivity(go_enter);
            this.finish();
        }

    }


    // 要申请的权限
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};


    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {

        new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("由于乐粮乐成长需要获取存储空间，为你存储个人信息；\n否则，您将无法正常使用乐粮乐成长")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startRequestPermission();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 开始提交请求权限
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限
    private AlertDialog dialog;

    private void showDialogTipUserGoToAppSettting() {

        dialog = new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("请在-应用设置-权限-中，允许乐粮乐成长使用存储权限来保存用户数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // 表示 调用照相机拍照
            case IMAGE_RESULT_CODE:
                if (resultCode == RESULT_OK) {
//                    Bundle bundle = data.getExtras();
//                    Bitmap bitmap = (Bitmap) bundle.get("data");
//                    bindingImg.setBackgroundColor(getResources().getColor(R.color.backg));
//                    bindingImg.setImageBitmap(bitmap);
                    Uri imageUri = null;
                    if (data != null) {
                        if (data.hasExtra("data")) {
                            Bitmap thunbnail = data.getParcelableExtra("data");
                            bindingImg.setImageBitmap(thunbnail);
                        }
                    }
                    path = mOutPutFileUri.getPath();
                    path = SavaImage(getBitmapByWidth(path, 100, 100), paths);
                    Query(3, "");
                }
                break;
            // 选择图片库的图片
            case PICK:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    bindingImg.setBackgroundColor(getResources().getColor(R.color.backg));
                    bindingImg.setImageURI(uri);
                    String[] proj = {MediaStore.Images.Media.DATA};
                    //好像是android多媒体数据库的封装接口，具体的看Android文档
                    Cursor cursor = managedQuery(uri, proj, null, null, null);
                    //按我个人理解 这个是获得用户选择的图片的索引值
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    //将光标移至开头 ，这个很重要，不小心很容易引起越界
                    cursor.moveToFirst();
                    //最后根据索引值获取图片路径
                    path = cursor.getString(column_index);
                    Query(3, "");
                }
                break;
            case CHOOSE_PICTURE:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    bindingImg.setBackgroundColor(getResources().getColor(R.color.backg));
                    bindingImg.setImageURI(uri);
                    String[] proj = {MediaStore.Images.Media.DATA};
                    //好像是android多媒体数据库的封装接口，具体的看Android文档
                    Cursor cursor = managedQuery(uri, proj, null, null, null);
                    //按我个人理解 这个是获得用户选择的图片的索引值
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    //将光标移至开头 ，这个很重要，不小心很容易引起越界
                    cursor.moveToFirst();
                    //最后根据索引值获取图片路径
                    path = cursor.getString(column_index);
                    Query(3, "");
                }
                break;
            case 123:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 检查该权限是否已经获取
                    int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        // 提示用户应该去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }


    /**
     * 保存位图到本地
     *
     * @param bitmap
     * @param path   本地路径
     * @return void
     */
    public String SavaImage(Bitmap bitmap, String path) {
        if (bitmap == null) {
            Log.e("bitmap", "空");
        }
        File file = new File(path + "/yasuo", System.currentTimeMillis() + ".jpg");
        Log.e("file", file.getPath());
        FileOutputStream fileOutputStream = null;
        try {
            //文件夹不存在，则创建它
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();

            }
            if (!file.exists()) {
                file.createNewFile();
                fileOutputStream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
            } else {
//                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.toString();
    }

    /**
     * 根据宽度从本地图片路径获取该图片的缩略图
     *
     * @param localImagePath 本地图片的路径
     * @param width          缩略图的宽
     * @param addedScaling   额外可以加的缩放比例
     * @return bitmap 指定宽高的缩略图
     */
    public static Bitmap getBitmapByWidth(String localImagePath, int width,
                                          int addedScaling) {
        if (TextUtils.isEmpty(localImagePath)) {
            return null;
        }

        Bitmap temBitmap = null;

        try {
            BitmapFactory.Options outOptions = new BitmapFactory.Options();

            // 设置该属性为true，不加载图片到内存，只返回图片的宽高到options中。
            outOptions.inJustDecodeBounds = true;

            // 加载获取图片的宽高
            BitmapFactory.decodeFile(localImagePath, outOptions);

            int height = outOptions.outHeight;
            Log.e("height", outOptions.outHeight + "-- outOptions.outWidth:" + outOptions.outWidth);
            if (outOptions.outWidth > width) {
                // 根据宽设置缩放比例
                outOptions.inSampleSize = outOptions.outWidth / (width + 1
                        + addedScaling);
                outOptions.outWidth = width;

                // 计算缩放后的高度
                height = outOptions.outHeight / outOptions.inSampleSize;
                outOptions.outHeight = height;
            }

            // 重新设置该属性为false，加载图片返回
            outOptions.inJustDecodeBounds = false;
            outOptions.inPurgeable = true;
            outOptions.inInputShareable = true;
            temBitmap = BitmapFactory.decodeFile(localImagePath, outOptions);
        } catch (Throwable t) {
            t.printStackTrace();
        }

        return temBitmap;
    }


    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx;
                if (options1Items.get(options1).getPickerViewText().equals(options2Items.get(options1).get(options2))) {
                    tx = options1Items.get(options1).getPickerViewText() +
                            options3Items.get(options1).get(options2).get(options3);
                } else {
                    tx = options1Items.get(options1).getPickerViewText() +
                            options2Items.get(options1).get(options2) +
                            options3Items.get(options1).get(options2).get(options3);
                }


                bindingArea.setText(tx);
                Query(options1Items.get(options1).getPickerViewText(),
                        options2Items.get(options1).get(options2),
                        options3Items.get(options1).get(options2).get(options3));
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<ProvinceJsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCity().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCity().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCity().get(c).getArea() == null
                        || jsonBean.get(i).getCity().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCity().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCity().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        handler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    private ArrayList<ProvinceJsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    public ArrayList<ProvinceJsonBean> parseData(String result) {//lgansquare 解析
        ArrayList<ProvinceJsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            for (int i = 0; i < data.length(); i++) {
                ProvinceJsonBean entity = LoganSquare.parse(data.optJSONObject(i).toString(), ProvinceJsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    /**
     * 隐藏系统键盘
     */
    public static void hideKeyBoard(Context ctx, View view) {
        InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 修改个人信息
     */
    private void Query(int select, String data) {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
//        RequestBody userno = RequestBody.create(MediaType.parse("text/plain"), share.getString("userno", ""));
        loginParams.put("userNo", share.getString("userno", ""));
        if (select == 1) {
//            RequestBody datas = RequestBody.create(MediaType.parse("text/plain"), data);
            loginParams.put("nickname", data);
        }
        if (select == 2) {
//            RequestBody datas = RequestBody.create(MediaType.parse("text/plain"), data);
            loginParams.put("sex", data);
        }
        if (select == 3) {
            Map<String, RequestBody> IMGloginParams = new HashMap<>();
            RequestBody usernos = RequestBody.create(MediaType.parse("text/plain"), share.getString("userno", ""));
            IMGloginParams.put("userNo", usernos);
            File f = new File(path);
            if (f != null && f.exists()) {
                RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), f);  //image/jpeg
                IMGloginParams.put("handPic\";filename=\"zsxx+" + share.getString("userno", ""), fileBody);
                imgtoStr(IMGloginParams);
            }
            return;
        }
        toStr(loginParams);
    }

    //返回字符串类型
    private void imgtoStr(Map<String, RequestBody> loginParams) {
        System.out.println("开始设置头像");
        up.show();
        ApiService.getInstance(this).PERSONAL_CHANGE_INFO_IMG_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    /**
     * 修改个人信息(重载)
     */
    private void Query(String province, String city, String district) {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
//        RequestBody datas = RequestBody.create(MediaType.parse("text/plain"), share.getString("userno", ""));
        loginParams.put("userNo", share.getString("userno", ""));
//        RequestBody provinces = RequestBody.create(MediaType.parse("text/plain"), province);
        loginParams.put("province", province);
//        RequestBody citys = RequestBody.create(MediaType.parse("text/plain"), city);
        loginParams.put("city", city);
//        RequestBody districts = RequestBody.create(MediaType.parse("text/plain"), district);
        loginParams.put("district", district);
//        loginParams.put("userNo", share.getString("userno", ""));
//        loginParams.put("province", province);
//        loginParams.put("city", city);
//        loginParams.put("district", district);
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).PERSONAL_CHANGE_INFO_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    /**
     * 查询个人信息
     */
    private void QueryNews() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userNo", share.getString("userno", ""));
        QuerytoStr(loginParams);
    }

    //返回字符串类型
    private void QuerytoStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).GET_PERSONAL_INFO_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = QUERY;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


}
